// sdk api
import {
	request
} from './utils/http';
import {
	authorize,
	createUserInfoButton,
	getLaunchOptionsSync,
	getStorageSync,
	removeStorageSync,
	getSystemInfo,
	getUserInfo,
	login,
	Modal,
	navigateToMiniProgram,
	openCustomerService,
	payment,
	previewQrCode,
	setClipboardContent,
	setStorageSync,
	Toast,
} from './utils/utils';
import { deBug } from './config.js';

//初始化
function initStart(params) {
	return new Promise((resolve, reject) => {
		request({
			url: '/api/game/init',
			data: params,
			method: 'POST',
		}).then(result=>{
			setStorageSync('cs_request_id', result.csRequestId)
			resolve(result)
		}).catch(err=>{
			reject(err)
		})
	})
}

//获取getOpenId
function getOpenId(params) {
	return new Promise((resolve, reject) => {
		request({
			url: '/api/user/getOpenId',
			data: params,
			method: 'POST',
		}).then(result=>{
			//setStorageSync('open_id', result.openId)
			setStorageSync('token', result.token)
			resolve(result)
		}).catch(err=>{
			reject(err)
		})
	})
}

//激活
function activate(params) {
	return request({
		url: '/api/user/activate',
		data: params,
		method: 'POST',
	})
}

//更新用户昵称，头像信息
function updateUserInfo(params){
	return request({
		url: '/api/user/update',
		data: params,
		method: 'POST',
	})
}

//后端登录接口
function userLogin() {
	return new Promise((resolve, reject) => {
		request({
			url: '/api/user/login',
			data: {},
			method: 'POST',
		}).then(result=>{
			resolve(result)
		}).catch(err=>{
			reject(err)
		})
	})
}

//后端登录上报接口
function reportLogin() {
	return new Promise((resolve, reject) =>{
		try {
			let count = 0;
			var timer = setInterval(function () {
				count++;
				let token = getStorageSync('token');
				if (token) {
					userLogin();
					clearInterval(timer)
				} else if (count > 16) {
					clearInterval(timer)
				}
			}, 500);
			resolve()
		} catch (e) {
			reject()
		}
	})
}

//退出登录
function logout() {
	return request({
		url: '/api/user/logout',
		data: {},
		method: 'POST',
	})
}

//上报
function report(params) {
	return request({
		url: '/api/game/report',
		data: params,
		method: 'POST',
	})
}

//支付宝上报
function aliPayReport(params) {
	const launchOption = getLaunchOptionsSync();
	params.query = JSON.stringify(launchOption.query) || '{}';
	return request({
		url: '/api/game/aliPayReport',
		data: params,
		method: 'POST',
	})
}

//场景打点上报
async function sceneReport(params) {
	const launchOption = getLaunchOptionsSync();
	const system = await getSystemInfo();
	let body = {
		cs_request_id: getStorageSync('cs_request_id') || '',
		platform: system.platform || 'android',
		query: JSON.stringify(launchOption.query) || '{}'
	};
	if (typeof params === 'string') {
		body.scene_name = params;
	} else if (typeof params === 'object' && params !== null) {
		body = {...body,...params};
	} else {
		throw new Error('Invalid input: params should be a string or an object');
	}
    return request({
        url: '/api/game/sceneReport',
        data: body,
        method: 'POST'
    });
}

//心跳呼吸
function heartbeat(params){
	return request({
		url: '/api/game/heartbeat',
		data: params,
		method: 'POST',
	})
}

//校验支付
function checkPay(params) {
	return request({
		url: '/api/order/check',
		data: params,
		method: 'POST',
	})
}

//创建订单
function createOrder(params){
	return request({
		url: '/api/order/create',
		data: params,
		method: 'POST',
	})
}

//支付结果回告服务端
function clientPayNotify(params){
	return request({
		url: '/api/order/notify',
		data: params,
		method: 'POST',
	})
}

//查询订单状态
function getOrderStatus(params){
	return request({
		url: '/api/order/getOrderStatus',
		data: params,
		method: 'POST',
	})
}


//检测文本内容
function checkTextContent(params){
	return new Promise((resolve, reject) => {
		request({
			url: '/api/game/checkTextContent',
			data: params,
			method: 'POST',
		}).then(result=>{
			if(result.check_result==1){
				resolve(result)
			}else{
				reject(result)
			}
		}).catch(err=>{
			resolve({'check_result':1})
		})
	})
}

//发送短信
function sendSmsCode(params){
	return request({
		url: '/api/user/sendSmsCode',
		data: params,
		method: 'POST',
	})
}

//绑定手机号
function bindMobile(params){
	return request({
		url: '/api/user/bindMobile',
		data: params,
		method: 'POST',
	})
}



//启动时执行
function appStartRun() {
	removeStorageSync('token');
	let launchOption = getLaunchOptionsSync();
	return new Promise((resolve, reject) => {
		getSystemInfo().then(system => {
			initStart({
				csRequestId: getStorageSync('cs_request_id') || '',
				platform: system.platform || '',
				system: system.system || '',
				sdkVersion: system.SDKVersion || '', 
				brand: system.brand || '',
				model: system.model || '',
				scene: launchOption.scene || '',
				query: JSON.stringify(launchOption.query) || '{}',
				referrerInfo: JSON.stringify(launchOption.referrerInfo) || '{}'
			}).then(initRes => {
				if(deBug){
					console.log(initRes)
				}
				login().then(loginResCode => {
					getOpenId({
						csRequestId: getStorageSync('cs_request_id'),
						code: loginResCode
					}).then((getOpenIdRes) => {
						if(deBug){
							console.log('注册完成', getOpenIdRes);
						}
						activate({
							csRequestId: getStorageSync('cs_request_id'),
							//openId: getOpenIdRes.openId,//不再返回
							query:JSON.stringify(launchOption.query) || '{}',
							referrerInfo: JSON.stringify(launchOption.referrerInfo) || '{}'
						}).then(result => {
							if(deBug){
								console.log('激活完成', result)
							}
							setInterval(function(){
								heartbeat({})//心跳
							},60000)
							resolve(result)
						}).catch(actErr => {
							reject(actErr)
						})
					}).catch(getOpenIdErr => {
						reject(getOpenIdErr)
					})
				}).catch(loginErr => {
					reject(loginErr)
				})
			}).catch(initErr => {
				reject(initErr)
			})
		}).catch(systemErr => {
			reject(systemErr)
		})
	})
}


//创建订单拉起支付
function payOrder(params){
	return new Promise((resolve, reject) => {
		getSystemInfo().then(system => {
			checkPay({
				platform: system.platform
			}).then(check=>{
				if(deBug){
					console.log('切支付', check)
				}
				if(check.switch_pay){
					createOrder({
						env:params.env || '0',
						platform: system.platform,
						switch_pay:check.switch_pay,
						prop_id:params.prop_id || '',
						buy_num:params.buy_num || '1',
						role_id:params.role_id,
						server_id:params.server_id,
						sku_id:params.sku_id || '',
						cp_order_id:params.cp_order_id,
						pay_amount:params.pay_amount,
						title:params.title || '',
						remark:params.remark || '',
						pay_callback_url:params.pay_callback_url || '',
						expand:params.expand || ''
					}).then(order=>{
						if(deBug){
							console.log('订单创建成功', order)
						}
						if(check.switch_pay===1){
							//预留传盛钱包支付
						}
						if(check.switch_pay===2){
							//渠道安卓内购支付
							payment(order).then(pay=>{
								clientPayNotify({
									result_action:'PAY_SUCCESS',
									outTradeNo:order.outTradeNo,
									errCode:pay.errCode || '',
									errMsg:pay.errMsg || '',
								})
								resolve(pay)
							}).catch(payErr=>{
								if(payErr.action=='CANCEL'){
									clientPayNotify({
										result_action:'PAY_CANCEL',
										outTradeNo:order.outTradeNo,
										errCode:payErr.errCode || '',
										errMsg:payErr.errMsg || '',
									})
								}else{
									clientPayNotify({
										result_action:'PAY_FAIL',
										outTradeNo:order.outTradeNo,
										errCode:payErr.errCode || '',
										errMsg:payErr.errMsg || '',
									})
								}
								reject(payErr)
							})
						}
						if(check.switch_pay===3){
						   //JSAPI，打开客服窗口支付
							openCustomerService({
								sessionFrom:order.order_no,
								showMessageCard:false,
								//sendMessageTitle:'订单支付',
								//sendMessageImg: require('./config').baseUrl + '/static/common/images/goods.jpg',
								success:function(opEes){
									
								},
								fail:function(opErr){
									
								},
						   });
							resolve(order);
						}
						if(check.switch_pay===4){
							//H5支付
							//复制粘贴到浏览器支付
							Modal('提示',order.show_message,false,'复制').then(copy=>{
								setClipboardContent(order.pay_url).then(ops=>{
									Toast('复制成功','success',1000);
								})
							})
							resolve(order)
						}
						if(check.switch_pay===5){
							//H5支付
							//二维码支付,
							Modal('', '打开支付二维码',false).then(mod=>{
								previewQrCode(order.show_qrcode_img);
							})
							resolve(order)
						}
						if(check.switch_pay===6){
						   //小程序支付
						   navigateToMiniProgram({
						      appId: check.mini_app_id,
						      path: 'pages/alipay/cs/pay?orderId=' + order.order_no + '&amount=' + params.pay_amount,
						   })
						   resolve(order)
						}
						//其它情况
						//resolve(order)
					}).catch(orderErr=>{
						reject(orderErr)
					})
				}else{
					if(deBug){
						console.log('渠道关闭了支付')
					}
					Modal('温馨提示',check.switch_pay_desc)
				}
			}).catch(checkErr=>{
				reject(checkErr)
			})
		})
	})
}

export default {
	appStartRun: appStartRun,
	login:reportLogin,
	logout:logout,
	report:report,
	sceneReport:sceneReport,
	payOrder:payOrder,
	checkTextContent:checkTextContent,
	sendSmsCode:sendSmsCode,
	bindMobile:bindMobile,
	getOrderStatus:getOrderStatus,
	aliPayReport:aliPayReport
}

